package com.project.shiro;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class ShiroRealm extends AuthorizingRealm {
    @Resource
    private IUserService userService;
//    @Resource
//    private IGradeService gradeService;
    //用户授权认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权验证");
        //1,获取当前登录的用户
//        UserBean userBean = (UserBean) principalCollection.getPrimaryPrincipal();
//        //2,通过SimpleAuthenticationInfo做授权
        SimpleAuthorizationInfo simpleAuthorizationInfo =
                new SimpleAuthorizationInfo();
//        //3,获取该用户的角色集合
//        List<RoleBean> roleBeanList = userBean.getRoleBeanList();
//        //4,遍历角色集合，将每个角色名放入到授权中
//        for (RoleBean roleBean : roleBeanList){
//            simpleAuthorizationInfo.addRole(roleBean.getName());
//        }
//        //3,获取该用户的权限集合
//        List<GradeBean> gradeBeanList = gradeService.findByRoleList(roleBeanList);
//        for(GradeBean gradeBean:gradeBeanList){
//            simpleAuthorizationInfo.addStringPermission(gradeBean.getName());
//        }

        return simpleAuthorizationInfo;
    }

    //用户登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1,获取用户名,如果为空表示没有登录
        String userName = (String) authenticationToken.getPrincipal();
        if(userName == null || userName.equals("")){
            return null;
        }
        //2，根据用户名获取用户数据中信息，为null表示该用户不存在或已删除。
        UserBean userBean =  userService.findByName(userName);
        if(userBean == null){
            return null;
        }
        //3,将目前从数据库获取的最新的正确数据，注入到securityManager中，
        // 自动和登录时传入的数据比对
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(userBean,userBean.getPwd(),getName());

        return simpleAuthenticationInfo;
    }
}
